import pymysql
import psycopg2


class Operator:
    @staticmethod
    def execute(ds):
        # 字段信息
        col = ()
        # 字段内容
        data = []
        dbtype = str.lower(ds.dbtype)
        # 根据数据库类型，读取对应的设计文档sql脚本
        if dbtype == 'mysql':
            operator = pymysql
        elif dbtype == 'postgres':
            operator = psycopg2
        else:
            raise Exception("该数据库类型暂不支持！具体类型请查看readme文档")
        # sql脚本的名称就是数据库的名称
        with open("./sql/" + dbtype + ".sql", 'r', encoding='utf8') as fp:
            sql = fp.read().replace("\n", " ").replace("\t", " ")
        conn = operator.connect(host=ds.host, port=ds.port, user=ds.username, password=ds.password,
                                database=ds.database)
        cursor = conn.cursor()
        # 获取指定表的设计文档
        for table in ds.tables:
            tempSql = str.format(sql, table)
            cursor.execute(tempSql)
            col = cursor.description
            data.append(cursor.fetchall())
        cursor.close()
        conn.close()
        return data, col
